#include "stm32f1xx_hal.h"

#define TB6612_AIN1_Port    GPIOB     
#define TB6612_AIN2_Port    GPIOB    
#define TB6612_BIN1_Port    GPIOB   
#define TB6612_BIN2_Port    GPIOB          //引脚宏定义

#define TB6612_AIN1_Pin    GPIO_PIN_12
#define TB6612_AIN2_Pin    GPIO_PIN_13
#define TB6612_BIN1_Pin    GPIO_PIN_14
#define TB6612_BIN2_Pin    GPIO_PIN_15

#define Max_Speed    100                   //正转速度最大值
#define Min_Speed    -100                  //反转速度最大值

extern TIM_HandleTypeDef htim1;            //外部引用定时器1

void Motor_SetSpeed(int Motor1, int Motor2)//前进极性:(+, -),后退极性:(-, +)
{
    if(Motor1 > 0)
    {
        HAL_GPIO_WritePin(TB6612_AIN1_Port, TB6612_AIN1_Pin, GPIO_PIN_SET);
        HAL_GPIO_WritePin(TB6612_AIN2_Port, TB6612_AIN2_Pin, GPIO_PIN_RESET);
    }
    else if(Motor1 < 0)
    {
        HAL_GPIO_WritePin(TB6612_AIN1_Port, TB6612_AIN1_Pin, GPIO_PIN_RESET);
        HAL_GPIO_WritePin(TB6612_AIN2_Port, TB6612_AIN2_Pin, GPIO_PIN_SET);
        Motor1 = -Motor1;
    }
    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, Motor1);//输入PWM数值

    if(Motor2 < 0)
    {
        HAL_GPIO_WritePin(TB6612_BIN1_Port, TB6612_BIN1_Pin, GPIO_PIN_SET);
        HAL_GPIO_WritePin(TB6612_BIN2_Port, TB6612_BIN2_Pin, GPIO_PIN_RESET);
        Motor2 = -Motor2;
    }
    else if(Motor2 > 0)
    {
        HAL_GPIO_WritePin(TB6612_BIN1_Port, TB6612_BIN1_Pin, GPIO_PIN_RESET);
        HAL_GPIO_WritePin(TB6612_BIN2_Port, TB6612_BIN2_Pin, GPIO_PIN_SET);
    }
    __HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, Motor2);//输入PWM数值
}

void Speed_Limit(int *Motor1, int *Motor2)//速度限幅
{
    if(*Motor1 > Max_Speed) *Motor1 = Max_Speed;
    if(*Motor1 < Min_Speed) *Motor1 = Min_Speed;

    if(*Motor2 > Max_Speed) *Motor2 = Max_Speed;
    if(*Motor2 < Min_Speed) *Motor2 = Min_Speed;
}
